/*
 * @Author: jiayu
 * @Date: 2022-08-04 16:12:56
 * @LastEditors: jiayu
 * @LastEditTime: 2023-11-07 17:00:46
 * @Description:
 */
import Card from '@/components/Card';
import { Bar, } from '@ant-design/plots';
import { Button, Popover, DatePicker } from 'antd';
import { Dispatch, memo, SetStateAction, useCallback, useEffect, useMemo, useState } from 'react';
import styles from './index.less';

import { FullscreenOutlined, FullscreenExitOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import React from 'react';
import { instance } from '@/services/jy-api/api';
import { useOrganizationalStore } from '';
import moment from 'moment';
import { useModel } from '@umijs/max';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY/MM/DD';

const RightContentRender: React.FC<ChartSctionProps> = (props) => {
  const { isModal, full, fullHandle, dateChange, defaultDeteValue } = props
  const click = () => {
    if (isModal) {
      full && full(false)
    } else {
      fullHandle && fullHandle('section1')
      full && full(true)
    }
  }
  // return null
  return <div className={styles.rightToolBar}>
    <RangePicker defaultValue={defaultDeteValue} format={dateFormat} style={{ marginRight: 10 }} onChange={dateChange} />
    <Button icon={isModal ? <FullscreenExitOutlined /> : <FullscreenOutlined />} onClick={click}></Button>
  </div>
}

export interface ChartSctionProps {
  isModal?: boolean,
  full?: Dispatch<SetStateAction<boolean>>
  fullHandle?: (val: string) => void
  dateChange?: (val: any) => void,
  defaultDeteValue: any
}

const Index: React.FC<ChartSctionProps> = memo((props) => {
  const [config, setConfig] = useState<any>()
  const { currentDepartmentId } = useModel('organizational')
  const [datePick, setDatePick] = useState([moment(moment().add(-6, 'M'), dateFormat), moment(moment(), dateFormat)])
  const [departmentId, setDepartmentId] = useState('')
  const [departmentName, setDepartmentName] = useState('')
  const getData = () => {
    instance('/index/Screen/studyDuration', {
      params: {
        department_id: currentDepartmentId,
        stime: moment(datePick[0]).format('YYYY-MM-DD'),
        etime: moment(datePick[1]).format('YYYY-MM-DD'),
      }
    }).then(data => {
      if (!data.data) {
        return
      }
      data.data.forEach(item => {
        item.short_name = item.short_name || item.title
      })
      setDepartmentId(data.data[0].id)
      setDepartmentName(data.data[0].short_name)
      const config = {
        data: data.data,
        xField: 'learn_num',
        yField: 'short_name',
        seriesField: 'short_name',
        xAxis: {
          label: {
            style: {
              fill: '#ffffff',
              fontSize: 14
            },
            // 数值格式化为千分位
            formatter: (v: any) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
          },
          grid: {
            line: {
              style: {
                stroke: '#8291A9',
                lineWidth: 1,
                lineDash: [4, 5],
                strokeOpacity: 0.7,
              }
            }
          }
        },
        yAxis: {
          label: {
            style: {
              fill: '#ffffff',
              fontSize: 14
            },
          },
        },
        tooltip: {
          title: (val: string) => {
            return `${val} 平均学习时长（分钟）`
          },
          // domStyles: {
          //   'g2-tooltip-title': {
          //     color: 'red'
          //   }
          // }
        },
        legend: {
          flipPage: false,
          itemName: {
            style: {
              fill: '#ffffff',
              fontSize: 14
            },
          },
          position: 'top-left',
          marker: {
            style: (x: { r: 5, fill: '#5AD8A6', fillOpacity: 1, stroke: null }) => {
              return {
                ...x,
                r: 10,
              }
            },
          }
        },
        maxBarWidth: 20,
        interactions: [
          // {
          //   type: 'element-selected',
          // },
          {
            type: 'element-single-selected',
          },
        ],
        state: {
          // 设置 active 激活状态的样式
          active: {
            animate: { duration: 100, easing: 'easeLinear' },
            style: {
              lineWidth: 2,
              stroke: '#000',
            },
          },
        }
      }
      setConfig(config)
    })
  }
  useEffect(() => {
    if (currentDepartmentId) {
      getData()
    }
  }, [currentDepartmentId, datePick]);

  const Title = () => {
    return <div className={styles.titleContainer}>
      <div className={styles.title}>培训课程平均学习时长</div>
      <Popover content="培训课程平均学习时长描述了该部门的平均每人每月的学习时长(所有人学习总时长÷人数)">
        <ExclamationCircleOutlined className={styles.icon} />
      </Popover>
    </div>
  }
  const dateChange = useCallback((e) => {
    console.log(e)
    if (e) {
      setDatePick(e)
    }
  }, [])

  const chartOnClick = (plot) => {
    plot.on('plot:click', (evt) => {
      const { x, y } = evt;
      const tooltipData = plot.chart.getTooltipItems({ x, y });
      setDepartmentName(tooltipData[0].data.short_name)
      setDepartmentId(tooltipData[0].data.id)
    });
  }

  return (
    <div className={styles.section} id="section1">
      <Card TitleRnder={<Title />} RightContentRender={<RightContentRender {...props} dateChange={dateChange} defaultDeteValue={datePick} />}>
        <div className={styles.container}>
          <div className={styles.left}>
            {config && <Bar height={300} {...config} onReady={chartOnClick} />}
          </div>
          <div className={styles.right}>
            <div className={styles.title}>{departmentName}人员学习排名</div>
            {
              departmentId && <Chart2 department_id={departmentId} date={datePick} />
            }
          </div>
        </div>
      </Card>
    </div>
  );
});

const Chart2 = (props: {
  department_id: string,
  date: any
}) => {
  const {
    department_id,
    date
  } = props
  const [config, setConfig] = useState<any>()
  const getData = () => {
    instance('/index/Screen/learningRecord', {
      params: {
        start_time: moment(date[0]).format('YYYY-MM-DD'),
        end_time: moment(date[1]).format('YYYY-MM-DD'),
        department_id: department_id
      }
    }).then(data => {
      const _config = {
        appendPadding: [0, 38, 0, 0],
        data: data.data?.sort((a, b) => b.learn_time - a.learn_time).slice(0, 10) || [],
        xField: 'learn_time',
        yField: 'name',
        seriesField: 'name',
        legend: false,
        interactions: [{ type: 'element-active' }],
        maxBarWidth: 20,
        label: {
          // 可手动配置 label 数据标签位置
          position: 'right',
          offset: 4,
          style: {
            fill: '#ffffff',
            fontSize: 12
          },
          formatter: (v: any) => {
            return v.learn_time + '分钟'
          },
        },
        barStyle: {
          radius: [8, 8, 0, 0],
        },
        xAxis: {
          label: {
            // 数值格式化为千分位
            formatter: (v: any) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
          },
          grid: {
            line: {
              style: {
                stroke: '#8291A9',
                lineWidth: 1,
                lineDash: [4, 5],
                strokeOpacity: 0.7,
              }
            }
          }
        },
        state: {
          // 设置 active 激活状态的样式
          selected: {
            animate: { duration: 100, easing: 'easeLinear' },
            style: {
              lineWidth: 2,
              stroke: '#000',
            },
          },
        }
      }
      setConfig(_config)
    })
  }
  useEffect(() => {
    getData()
  }, [department_id, date])
  if (!config) {
    return null
  }
  return <Bar height={300} {...config} />;
}

export default Index;

